package com.itany.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Author：汤小洋
 * Date：2022-11-11 10:09
 * Description：<描述>
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            // 解析表单数据
            List<FileItem> items = upload.parseRequest(req);
            for(FileItem item : items){
                // 判断是普通的文本数据还是文件数据
                if(item.isFormField()){ // 普通文本
                    System.out.println("参数名："+item.getFieldName());
                    System.out.println("参数值："+item.getString("utf-8"));
                }else{ // 文件
                    System.out.println("文件名："+item.getName());
                    System.out.println("文件大小："+item.getSize());
                    System.out.println("文件类型："+item.getContentType());

                    // 为文件重命名，确保文件名唯一
                    String fileName = UUID.randomUUID().toString() + item.getName().substring(item.getName().lastIndexOf("."));
                    // 获取upload目录的物理路径
                    System.out.println("upload目录的物理路径：" + req.getServletContext().getRealPath("upload"));
                    String pathName = req.getServletContext().getRealPath("upload") + File.separator + fileName;
                    System.out.println(pathName);

                    // 写入保存文件（在IDEA中，默认情况下，IDEA不会发布部署空文件夹，可以先在upload文件夹中随便创建一个文件）
                    item.write(new File(pathName));

                    resp.getWriter().print("success");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
